package cn.edu.zut.controller;


import cn.edu.zut.domin.BookIndex;
import cn.edu.zut.service.IBookIndexService;
import com.github.pagehelper.PageInfo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/bookIndex")
public class BookIndexController {
    //加载配置文件
    private ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    //获取对象
    private IBookIndexService bookIndexService =(IBookIndexService)ac.getBean("bookIndexServiceImpl");

    @RequestMapping("/findAll")
    //默认第一页,每页显示四个
    public ModelAndView findAll(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                @RequestParam(name = "size", required = true, defaultValue = "4") int size) throws Exception {
        ModelAndView mv = new ModelAndView();
        List<BookIndex> bookIndices = bookIndexService.findAll(page, size);
        //分页Bean PageInfo就是一个分页的Bean
        PageInfo<BookIndex> pageInfo = new PageInfo<>(bookIndices);
        //总页数等....
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("BookIndex-list");
        return mv;
    }

    @RequestMapping("/save")
    public String saveBookIndex(BookIndex bookIndex) throws Exception {
        bookIndexService.saveBookIndex(bookIndex);
        return "redirect:findAll";
    }

    @RequestMapping("/delete")
    public String deleteBookIndexByTypeId(String typeId) throws Exception {
        System.out.println(typeId);
        bookIndexService.deleteBookIndex(typeId);
        //删除完成后回到全部信息页面
        return "redirect:findAll";
    }


    @RequestMapping("/update")
    public String updateBookIndex(BookIndex bookIndex) throws Exception {
        bookIndexService.updateBookIndex(bookIndex);
        return "redirect:findAll";
    }


    @RequestMapping("/findBookByTypeId")
    public ModelAndView findByBookIndexName(String typeId) throws Exception {
        System.out.println(typeId);
        ModelAndView mv = new ModelAndView();
        List<BookIndex> bookIndices = bookIndexService.findBookIndexByTypeId(typeId);
        mv.addObject("bookIndexList", bookIndices);
        mv.setViewName("BookIndex-list");
        return mv;
    }

}
